#import "BWTableView.h"

@implementation BWTableView


// make return and tab only end editing, and not cause other cells to edit

- (void) textDidEndEditing: (NSNotification *) notification
{
    NSDictionary *userInfo = [notification userInfo];
    
    int textMovement = [[userInfo valueForKey:@"NSTextMovement"] intValue];
    
    if (textMovement == NSReturnTextMovement 
        || textMovement == NSTabTextMovement
        || textMovement == NSBacktabTextMovement) {
        
        NSMutableDictionary *newInfo;
        newInfo = [NSMutableDictionary dictionaryWithDictionary: userInfo];
        
        [newInfo setObject: [NSNumber numberWithInt: NSIllegalTextMovement]
                 forKey: @"NSTextMovement"];
        
        notification = 
            [NSNotification notificationWithName: [notification name]
                                       object: [notification object]
                                       userInfo: newInfo];
        
        [super textDidEndEditing: notification];
        
        [[self window] makeFirstResponder:self];
    }
    
} // textDidEndEditing


// --------------------------------------------------

- (void) setRowHighlightColor: (NSColor *) color
{
    [color retain];
    [rowHighlightColor release];
    
    rowHighlightColor = color;
    [self setNeedsDisplay: YES];

} // setRowHighlightColor



- (void) setRowHighlightIndexes: (NSIndexSet *) indexes
{
    [rowHighlightIndexes release];
    rowHighlightIndexes = [indexes copy];
} // setRowHighlightIndexes

- (void) dealloc
{
    [rowHighlightIndexes release];
    [rowHighlightColor release];
    [super dealloc];
} // dealloc


// cargo-culted from Dan Wood's code at 
// http://www.gigliwood.com/tabletester/>

- (void) highlightSelectionInClipRect: (NSRect) clipRect
{
    float rowHeight = [self rowHeight] + [self intercellSpacing].height;
    NSRect visibleRect = [self visibleRect];

    NSRect highlightRect;
    highlightRect.origin = NSMakePoint(NSMinX(visibleRect), 
                                       (int)(NSMinY(clipRect)/rowHeight)*rowHeight);
    highlightRect.size = NSMakeSize(NSWidth(visibleRect), rowHeight - [self intercellSpacing].height);
        
    while (NSMinY(highlightRect) < NSMaxY(clipRect)) {
        NSRect clippedHighlightRect = NSIntersectionRect(highlightRect, clipRect);
        int row = (int)((NSMinY(highlightRect)+rowHeight/2.0)/rowHeight);
        if ([rowHighlightIndexes containsIndex: row]) {
            [rowHighlightColor set];
            NSRectFill(clippedHighlightRect);
        }
        highlightRect.origin.y += rowHeight;
    }
        
    [super highlightSelectionInClipRect: clipRect];

} // highlightSelectionInClipRect


@end // BWTableView

